package com.baizhi.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import javax.annotation.Resource;
import java.util.Set;

@Aspect
@Configuration
public class CacheAspect {
    @Resource
    StringRedisTemplate stringRedisTemplate;
    @Resource
    RedisTemplate redisTemplate;

   // @Around("@annotation(com.baizhi.annotation.AddCache)")
    public Object addCache(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {

        System.out.println("***************进入环绕通知***************");

        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());

        //拼接字符串
        StringBuilder stringBuilder = new StringBuilder();
        //获取类的全限定名
        String ClassName = proceedingJoinPoint.getTarget().getClass().getName();
        stringBuilder.append(ClassName);
        stringBuilder.append("-");
        //获取方法名
        String methodName = proceedingJoinPoint.getSignature().getName();
        stringBuilder.append(methodName);
        stringBuilder.append("-");
        //获取参数的数组
        Object[] args = proceedingJoinPoint.getArgs();
        //遍历数组
        for (Object arg : args) {
            stringBuilder.append(arg);
        }
        //获取String类型的操作
        ValueOperations StringOps = redisTemplate.opsForValue();
        //获取拼接好的key
        String key = stringBuilder.toString();
        //判断该key 是否在redis 中存在
        Boolean aBoolean = redisTemplate.hasKey(key);
        Object result =null;
        if(aBoolean){
            //存在取出数据返回缓存数据
            result = StringOps.get(key);
        }else{
            //不存在
            //放行方法
            result = proceedingJoinPoint.proceed();
            //添加缓存
            StringOps.set(key,result);
        }
        return result;
    }
   // @AfterReturning("@annotation(com.baizhi.annotation.DelCache)")
    public void delCache(JoinPoint joinPoint){
        System.out.println("--------------清除缓存-------------");
        //清除缓存
        //获取类的全限定类名
        String ClassName = joinPoint.getTarget().getClass().getName();
        //获取所有的key
        Set<String> keys = stringRedisTemplate.keys("*");
        //遍历所有的key
        for (String key : keys) {
            //判断key是否是该方法的全限定类名
            if(key.startsWith(ClassName)){
                //删除key
                stringRedisTemplate.delete(key);
            }
        }
    }
}
